using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.Forms;
using ctsu.BaseForms;
using ctsu.Security;

using Syncfusion.Windows.Forms.Tools;
using ctsu.Shared;
using ctsu.Data;

namespace ctsu.Admin.BusLogic
{
	public class BLFormPatientImpl : BLFormBaseImpl
	{
		public BLFormPatientImpl(FormMain formMain, FormBase form, FormInfoBase formInfo, DataTable tableSchema, Permission formSecurity, Hashtable configData)
			: base(formMain, form, formInfo, tableSchema, formSecurity, configData)
		{

		}

		protected override bool VerifyAll()
		{
			Control ctl = Forms.Utils.GetControlByName("LastName", this._form.Controls);
			if (ctl.Text.Trim().Length == 0)
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("WARNING: New patient reocord does not have a last name!");
				sb.Append(Environment.NewLine);
				sb.Append("Do you want to continue saving?");
				if (MessageBox.Show(this._form, sb.ToString(), "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
					return false;
			}
			return base.VerifyAll();
		}

		protected virtual bool VerifyDOB(Control ctl)
		{
			FieldContext fc = (FieldContext)ctl.Tag;
			//bool retVal = true;
			//string message = "";
			Syncfusion.Windows.Forms.Tools.DateTimePickerAdv dt = (DateTimePickerAdv)ctl;

			if (dt.IsNullDate)
				return true;

			if (dt.Value > DateTime.Today)
			{
				fc.ErrorMessage = "Date of birth can not be greater than today's date!";
				return false;
			}
			return true;
		}

		protected virtual bool VerifyIdentifier(Control ctl)
		{
			StringBuilder sb = new StringBuilder();
			//bool retVal = true;
			string message = "";
			FieldContext fcMRN = null;
			FieldContext fcOtherID = null;

			FieldContext fc = (FieldContext)ctl.Tag;
			string name = fc.Control.Name;
			string sValue = "";

			if (name == "MRN")
			{
				fcMRN = fc;
				fcOtherID = (FieldContext)this._fcManager.Item("OtherPatientID");
			}
			else
			{
				fcOtherID = fc;
				fcMRN = (FieldContext)this._fcManager.Item("MRN");
			}

			if (Forms.Utils.IsMissingValue(fcMRN.Control) && Forms.Utils.IsMissingValue(fcOtherID.Control))
			{
				fc.ErrorMessage = "You must enter the MRN or Other Identifier.";
				return false;
			}

			try
			{
				sValue = fc.CurrentValue.ToString();
				int retID = 0;
				int patID = 0;

				if (this.FormMode == EditMode.Edit)
				{
					FieldContext fcID = (FieldContext)this._fcManager.Item("ID");
					patID = Convert.ToInt32(fcID.CurrentValue);
				}

				//check for duplicate identifier
				if (name == "MRN")
				{
					if (sValue.Length > 0)
					{
						if (IsDuplicate("MRN", sValue, out retID, patID))
						{
							sb.Append("MRN: " + sValue + " is already being used by Patient ID: " + retID);
							sb.Append(Environment.NewLine);
							sb.Append("Duplicate values are not allowed for this field");
							fc.ErrorMessage = sb.ToString();
							return false;
						}
					}
				}
				else if (name == "OtherPatientID")
				{
					//only check for other id if there is no mrn
					if (Forms.Utils.IsMissingValue(fcMRN.Control))
					{
						if (!IsOtherPatientIDCorrectFormat(sValue, out message))
						{
							sb.Append(message);
							sb.Append(Environment.NewLine);
							fc.ErrorMessage = sb.ToString();
							return false;
						}

						//now check for duplicate
						if (IsDuplicate("OtherPatientID", sValue, out retID, patID))
						{
							sb.Append("Other Identifier: " + sValue + " is already being used by Patient ID: " + retID);
							sb.Append(Environment.NewLine);
							sb.Append("Duplicate values are not allowed for this field");
							fc.ErrorMessage = sb.ToString();
							return false;
						}
					}
				}
				return true;
			}
			catch (Exception ex)
			{
				sb.Append("Could not check for duplicate identifier!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Check For Duplicate Identifier Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}
		}

		private bool IsOtherPatientIDCorrectFormat(string text, out string message)
		{
			message = "";
			StringBuilder sb = new StringBuilder();

			//check for a :
			int pos = text.IndexOf(":");
			if (pos == -1)
			{
				sb.Append("Incorrect format for Other Identifier!");
				sb.Append(Environment.NewLine);
				sb.Append("Format must be <id:protocol number>");
				sb.Append(Environment.NewLine);
				sb.Append("Example: id = 012345 and protocol number is 01-01-1234");
				sb.Append(Environment.NewLine);
				sb.Append("Correct format: 012345:01-01-1234");
				message = sb.ToString();
				return false;
			}

			//check to see if the protocol exists
			string protoNumber = text.Substring(pos + 1);
			string sql = "SELECT ID FROM Protocol WHERE ProtocolNumber ='" + protoNumber + "'";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				object o = DataAccess.GetScalarObject(CommandType.Text, sql);

				if (o == null)
				{
					sb.Append("Could not find protocol: " + protoNumber);
					sb.Append(Environment.NewLine);
					sb.Append("Make sure you have the correct protocol number!");
					message = sb.ToString();
					return false;
				}

			}
			catch (Exception ex)
			{
				sb.Append("Error in searchin for protocol number: " + protoNumber);
				sb.Append(Environment.NewLine);
				sb.Append("Error: " + ex.Message);
				message = sb.ToString();
				return false;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
			return true;
		}

		private bool IsDuplicate(string field, string val, out int retID, int patID)
		{
			retID = 0;
			string sql = "SELECT ID FROM Patient WHERE " + field + " ='" +
				val + "'";

			if (patID > 0)
				sql += " AND ID <>" + patID;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				object o = DataAccess.GetScalarObject(CommandType.Text, sql);

				if (o == null)
					return false;
				else
					retID = Convert.ToInt32(o);
				return true;
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}
	}
}
